package com.itheima.myreflect3;

import java.lang.reflect.Constructor;

/**
 * @program: Myset
 * @description: 反射获取构造方法并使用
 * @author: xuejingjing
 * @create: 2021-06-27 21:11
 **/
public class ReflectDemo1 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
//        method1();
//        method3();
//       method2();
        method4();
    }

    private static void method4() throws ClassNotFoundException, NoSuchMethodException {
        Class aClass = Class.forName("com.itheima.myreflect3.Student");
        //公共的私有的，都可以获取到。
        Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
        System.out.println("4:"+declaredConstructor);
        Constructor declaredConstructor1 = aClass.getDeclaredConstructor();
        System.out.println("4:"+declaredConstructor1);
        /**
         * 4:private com.itheima.myreflect3.Student(java.lang.String)
         * 4:public com.itheima.myreflect3.Student()
         */
    }

    private static void method2() throws ClassNotFoundException, NoSuchMethodException {
        Class aClass = Class.forName("com.itheima.myreflect3.Student");

        //1,获取Class对象

        //小括号中，一定要跟构造方法的形参保持一致
        Constructor constructor = aClass.getConstructor();
        System.out.println("2-1:"+constructor);
        Constructor constructor1 = aClass.getConstructor(String.class,int.class);
        System.out.println("2-2:"+constructor1);
        //因为Student类中，没有只有一个int的构造，所以这里会报错。
//        Constructor constructor2 = aClass.getConstructor(int.class);
        //这个构造器是私有的，所以也调用不到
        Constructor constructor3 = aClass.getConstructor(String.class);
        System.out.println("2-3:"+constructor3);

//        System.out.println("2-3:"+constructor2);
    }

    private static void method3() throws ClassNotFoundException {
        //1,获取Class对象
        Class aClass = Class.forName("com.itheima.myreflect3.Student");
        //获取到所有的构造方法
        Constructor[] declaredConstructors = aClass.getDeclaredConstructors();
        for (Constructor declaredConstructor : declaredConstructors) {
            System.out.println("3:"+declaredConstructor);
        }
        /**
         * 3:public com.itheima.myreflect3.Student(java.lang.String,int)
         * 3:public com.itheima.myreflect3.Student()
         * 3:private com.itheima.myreflect3.Student(java.lang.String)
         */
    }


    /**
     * 获取所有公共（public）构造方法对象的数组
     * @throws ClassNotFoundException
     */
    private static void method1() throws ClassNotFoundException {
        //1,获取Class对象
        Class aClass = Class.forName("com.itheima.myreflect3.Student");

        //返回所有公共（public）构造方法对象的数组
        Constructor[] constructors = aClass.getConstructors();

        for (Constructor constructor : constructors) {
            System.out.println("1111:"+constructor);
        }
    }
}
